package top.korori.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.korori.system.entity.bo.MyInfoBo;
import top.korori.system.entity.bo.PasswordBo;
import top.korori.system.enums.SysUserSex;
import top.korori.system.mapper.SysUserMapper;
import top.korori.system.service.SysMyService;
import top.korori.system.service.SysUserService;
import top.korori.system.utils.SysSecurityUtil;
import top.korori.system.entity.SysUser;
import top.korori.common.exception.BizException;
import top.korori.common.utils.EnumUtils;

@Service
public class SysMyServiceImpl implements SysMyService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public void editMyInfo(MyInfoBo myInfoBo) {

        Long userId = SysSecurityUtil.getUserId();

        if (ObjUtil.isNotNull(myInfoBo.getUserName())){
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getUserName,myInfoBo.getUserName());
            SysUser sysUser = sysUserMapper.selectOne(queryWrapper);

            if (ObjUtil.isNotNull(sysUser) && ObjUtil.notEqual(userId,sysUser.getUserId())) {
                throw new BizException("用户已存在,请输入其他用户名");
            }
            if (ObjUtil.isEmpty(myInfoBo.getUserName())){
                throw new BizException("用户不能为空");
            }
        }

        if (!ObjUtil.isNull(myInfoBo.getSex())){
            if (!EnumUtils.exist(SysUserSex::getSex,myInfoBo.getSex())){
                throw new BizException("非法性别");
            }
        }

        if (ObjUtil.isNotEmpty(myInfoBo.getPhone())){
            if(!Validator.isMobile(myInfoBo.getPhone())){
                throw new BizException("非法手机号");
            }
        }

        SysUser sysUser = BeanUtil.copyProperties(myInfoBo, SysUser.class);
        sysUser.setUserId(userId);
        sysUserMapper.updateById(sysUser);
    }

    @Override
    public void editPassword(PasswordBo passwordBo) {
        SysUser sysUser = sysUserService.getById(SysSecurityUtil.getUserId());
        String oldPassword = sysUser.getPassword();
        if (ObjUtil.notEqual(oldPassword,passwordBo.oldPassword)){
            throw new BizException("旧密码错误请重新输入");
        }
        sysUser.setPassword(passwordBo.newPassword);
        sysUserService.updateById(sysUser);
    }
}
